package com.example.ferry

import android.os.Bundle
import android.view.WindowManager
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import android.animation.ValueAnimator
import android.view.animation.LinearInterpolator
import android.view.ViewTreeObserver
import android.util.TypedValue
import android.os.Handler
import android.os.Looper
import java.util.concurrent.TimeUnit
import android.widget.FrameLayout
import android.util.Log
import java.text.SimpleDateFormat
import java.util.Date
import com.google.android.material.floatingactionbutton.FloatingActionButton
import android.view.MotionEvent
import android.graphics.drawable.Drawable
import androidx.core.content.ContextCompat

class MainActivity : AppCompatActivity() {
    private lateinit var lineContainers: Array<FrameLayout>
    private lateinit var controlPanel: FloatingActionButton
    private lateinit var sleepButton: FloatingActionButton
    private lateinit var motivationButton: FloatingActionButton
    private lateinit var luckButton: FloatingActionButton
    private lateinit var healthButton: FloatingActionButton
    private lateinit var focusButton: FloatingActionButton
    private lateinit var reflectButton: FloatingActionButton
    private var isControlPanelVisible = false
    private var isPaused = false
    private val playIcon: Drawable by lazy { ContextCompat.getDrawable(this, R.drawable.ic_play)!! }
    private val pauseIcon: Drawable by lazy { ContextCompat.getDrawable(this, R.drawable.ic_pause)!! }

    private val sleepSubtitles = arrayOf(
        arrayOf("00:00:00 太灵九宫"),
        arrayOf("00:00:00 太一守房"),
        arrayOf("00:00:00 百神参位"),
        arrayOf("00:00:00 魂魄和同"),
        arrayOf("00:00:00 长生不死"),
        arrayOf("00:00:00 塞灭邪凶")
    )

    private val motivationSubtitles = arrayOf(
        arrayOf("00:00:00 你无法再用几天的时间赶超别人几个月的努力"),
        arrayOf("00:00:00 落后就要挨打"),
        arrayOf("00:00:00 一颗向上的心脏"),
        arrayOf("00:00:00 不该有一副下坠的身躯"),
        arrayOf("00:00:00 去做具体的事"),
        arrayOf("00:00:00 然后稳稳托举自己"),
        arrayOf("00:00:00 庸人败于惰")
    )

    private val luckSubtitles = arrayOf(
        arrayOf("00:00:00 天时地利人和通"),
        arrayOf("00:00:00 阴阳五行运势通"),
        arrayOf("00:00:00 吉星高照福禄通")
    )

    private val healthSubtitles = arrayOf(
        arrayOf("00:00:00 退热口诀"),
        arrayOf("00:00:00 九江水帝，四渎源公"),
        arrayOf("00:00:00 满天降雪，遍地严霜"),
        arrayOf("00:00:00 朔风似箭，雹霰如倾"),
        arrayOf("00:00:00 退散邪热，保救安宁"),
        arrayOf("00:00:00 雪山万仞，冰煞斜精"),
        arrayOf("00:00:00 急急如律令")
    )

    private val focusSubtitles = arrayOf(
        arrayOf("00:00:00 将军赶路，不追小兔"),
        arrayOf("00:00:00 欲成大树，不与草争"),
        arrayOf("00:00:00 不要找借口，对不符合目标的事立刻说不"),
        arrayOf("00:00:00 只做最重要的事")
    )

    private val reflectSubtitles = arrayOf(
        arrayOf("00:00:00 我是真的在提升效率吗，", "00:00:08 我真的需要这些信息吗"),
        arrayOf("00:00:00 还是在为了逃避无聊而浪费时间？", "00:00:08 还是在囤积、纸上谈兵、避免无聊、陷入焦虑？"),
        arrayOf("00:00:00 圣人畏因，凡人畏果", "00:00:08 "),
        arrayOf("00:00:00 我做的事对我的目标有帮助吗，", "00:00:08 我正在学的东西有多大的概率会复习到？"),
        arrayOf("00:00:00 是逃避更难任务的借口？", "00:00:08 这真的重要到值得记忆和复习吗？"),
        arrayOf("00:00:00 还是仅仅能带来虚假的进步感？", "00:00:08 "),
        arrayOf("00:00:00 ", "00:00:08 我有多久没翻开一本非虚构的书籍了？")
    )

    private val handler = Handler(Looper.getMainLooper())
    private var isPlaying = false
    private var startTime: Long = 0
    private val dateFormat = SimpleDateFormat("HH:mm:ss")
    private val pendingDanmaku = mutableListOf<DanmakuData>()
    private var currentSubtitles = arrayOf<Array<String>>()

    data class DanmakuData(
        val text: String,
        val line: Int,
        val timestamp: String
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        try {
            // Set fullscreen
            window.setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN
            )
            
            setContentView(R.layout.activity_main)

            // Keep screen on
            window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)

            // Initialize line containers
            lineContainers = arrayOf(
                findViewById(R.id.line1),
                findViewById(R.id.line2),
                findViewById(R.id.line3),
                findViewById(R.id.line4),
                findViewById(R.id.line5),
                findViewById(R.id.line6),
                findViewById(R.id.line7)
            )

            // Initialize control buttons
            controlPanel = findViewById(R.id.controlPanel)
            sleepButton = findViewById(R.id.sleepButton)
            motivationButton = findViewById(R.id.motivationButton)
            luckButton = findViewById(R.id.luckButton)
            healthButton = findViewById(R.id.healthButton)
            focusButton = findViewById(R.id.focusButton)
            reflectButton = findViewById(R.id.reflectButton)

            // Set up click listeners
            controlPanel.setOnClickListener { togglePlayPause() }
            sleepButton.setOnClickListener { loadSubtitles(sleepSubtitles) }
            motivationButton.setOnClickListener { loadSubtitles(motivationSubtitles) }
            luckButton.setOnClickListener { loadSubtitles(luckSubtitles) }
            healthButton.setOnClickListener { loadSubtitles(healthSubtitles) }
            focusButton.setOnClickListener { loadSubtitles(focusSubtitles) }
            reflectButton.setOnClickListener { loadSubtitles(reflectSubtitles) }

            // Set initial subtitles
            currentSubtitles = reflectSubtitles
            loadSubtitles(currentSubtitles)

            // Start adding danmaku
            startDanmaku()
        } catch (e: Exception) {
            Log.e("MainActivity", "Error in onCreate: ${e.message}")
            e.printStackTrace()
        }
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                toggleControlPanel()
                return true
            }
        }
        return super.onTouchEvent(event)
    }

    private fun toggleControlPanel() {
        isControlPanelVisible = !isControlPanelVisible
        val visibility = if (isControlPanelVisible) View.VISIBLE else View.GONE
        controlPanel.visibility = visibility
        sleepButton.visibility = visibility
        motivationButton.visibility = visibility
        luckButton.visibility = visibility
        healthButton.visibility = visibility
        focusButton.visibility = visibility
        reflectButton.visibility = visibility
    }

    private fun togglePlayPause() {
        isPaused = !isPaused
        controlPanel.setImageDrawable(if (isPaused) playIcon else pauseIcon)
        
        // Pause or resume all existing danmaku animations
        lineContainers.forEach { container ->
            for (i in 0 until container.childCount) {
                val view = container.getChildAt(i)
                if (view is TextView) {
                    val animator = view.getTag(R.id.danmaku_animator) as? ValueAnimator
                    animator?.let {
                        if (isPaused) {
                            it.pause()
                        } else {
                            it.resume()
                        }
                    }
                }
            }
        }
    }

    private fun loadSubtitles(subtitles: Array<Array<String>>) {
        try {
            pendingDanmaku.clear()
            currentSubtitles = subtitles
            
            subtitles.forEachIndexed { lineIndex, lineSubtitles ->
                lineSubtitles.forEach { subtitle ->
                    val parts = subtitle.split(" ")
                    if (parts.size >= 2) {
                        val timestamp = parts[0]
                        val text = parts[1]
                        if (text.isNotEmpty()) {
                            pendingDanmaku.add(DanmakuData(text, lineIndex, timestamp))
                        }
                    }
                }
            }

            // Sort by timestamp
            pendingDanmaku.sortBy { dateFormat.parse(it.timestamp)?.time ?: 0 }
            
            // Clear existing danmaku
            lineContainers.forEach { it.removeAllViews() }
            
            // Reset time
            startTime = System.currentTimeMillis()
        } catch (e: Exception) {
            Log.e("MainActivity", "Error in loadSubtitles: ${e.message}")
            e.printStackTrace()
        }
    }

    private fun startDanmaku() {
        try {
            isPlaying = true
            startTime = System.currentTimeMillis()
            
            val runnable = object : Runnable {
                override fun run() {
                    if (isPlaying) {
                        try {
                            if (!isPaused) {
                                val currentTime = System.currentTimeMillis() - startTime
                                val currentTimeStr = String.format("%02d:%02d:%02d",
                                    TimeUnit.MILLISECONDS.toHours(currentTime),
                                    TimeUnit.MILLISECONDS.toMinutes(currentTime) % 60,
                                    TimeUnit.MILLISECONDS.toSeconds(currentTime) % 60
                                )

                                // Check if any danmaku should appear at current time
                                while (pendingDanmaku.isNotEmpty()) {
                                    val nextDanmaku = pendingDanmaku.first()
                                    if (nextDanmaku.timestamp == currentTimeStr) {
                                        addDanmakuToLine(nextDanmaku.text, nextDanmaku.line, currentTime)
                                        pendingDanmaku.removeAt(0)
                                    } else {
                                        break
                                    }
                                }
                            }
                        } catch (e: Exception) {
                            Log.e("MainActivity", "Error in runnable: ${e.message}")
                            e.printStackTrace()
                        }
                        
                        handler.postDelayed(this, 100) // Check every 100ms
                    }
                }
            }
            handler.post(runnable)
        } catch (e: Exception) {
            Log.e("MainActivity", "Error in startDanmaku: ${e.message}")
            e.printStackTrace()
        }
    }

    private fun addDanmakuToLine(text: String, line: Int, timestamp: Long) {
        try {
            if (line < 0 || line >= lineContainers.size) {
                Log.e("MainActivity", "Invalid line number: $line")
                return
            }
            
            val container = lineContainers[line]
            val danmakuText = TextView(this).apply {
                this.text = text
                setTextColor(android.graphics.Color.WHITE)
                textSize = 16f
                layoutParams = FrameLayout.LayoutParams(
                    FrameLayout.LayoutParams.WRAP_CONTENT,
                    FrameLayout.LayoutParams.WRAP_CONTENT
                )
            }
            
            container.addView(danmakuText)
            startAnimation(danmakuText, line)
        } catch (e: Exception) {
            Log.e("MainActivity", "Error in addDanmakuToLine: ${e.message}")
            e.printStackTrace()
        }
    }

    private fun startAnimation(danmakuText: TextView, line: Int) {
        try {
            danmakuText.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
                override fun onGlobalLayout() {
                    try {
                        danmakuText.viewTreeObserver.removeOnGlobalLayoutListener(this)
                        val screenWidth = resources.displayMetrics.widthPixels
                        val animator = ValueAnimator.ofFloat(screenWidth.toFloat(), -danmakuText.width.toFloat())
                        animator.duration = 10000 // 10 seconds to cross the screen
                        animator.interpolator = LinearInterpolator()
                        
                        // Store the animator in the view's tag for later access
                        danmakuText.setTag(R.id.danmaku_animator, animator)
                        
                        animator.addUpdateListener { animation ->
                            try {
                                danmakuText.translationX = animation.animatedValue as Float
                                // Remove danmaku when it's completely off screen
                                if (danmakuText.translationX + danmakuText.width < 0) {
                                    animator.cancel()
                                    lineContainers[line].removeView(danmakuText)
                                }
                            } catch (e: Exception) {
                                Log.e("MainActivity", "Error in animation update: ${e.message}")
                                e.printStackTrace()
                            }
                        }
                        animator.start()
                    } catch (e: Exception) {
                        Log.e("MainActivity", "Error in onGlobalLayout: ${e.message}")
                        e.printStackTrace()
                    }
                }
            })
        } catch (e: Exception) {
            Log.e("MainActivity", "Error in startAnimation: ${e.message}")
            e.printStackTrace()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        isPlaying = false
        handler.removeCallbacksAndMessages(null)
    }
}